<template>
  <div>
    <label :for="inputId" class="text-sm text-zinc-700 dark:text-white">{{ label }}</label>
    <div :id="id" class="relative">
      <AutoComplete
        :model-value="modelValue"
        @input="onInput"
        :input-id="inputId"
        :suggestions="items"
        @complete="search"
        unstyled
        option-label="label"
        :show-empty-message="false"
        :pt="ptConfig"
        @option-select="onOptionSelect"
      >
        <template #option="slotProps">
          <div v-tooltip.left="slotProps.option.value" class="flex items-center justify-between gap-4 px-2">
            <span>{{ slotProps.option.token }}</span>
            <div
              v-if="slotProps.option.isColor"
              class="border border-surface-200 dark:border-surface-700 w-4 h-4 rounded-full"
              :style="{ backgroundColor: slotProps.option.variable }"
            ></div>
            <div v-else class="text-xs max-w-16 text-ellipsis whitespace-nowrap overflow-hidden">
              {{ slotProps.option.value }}
            </div>
          </div>
        </template>
      </AutoComplete>
      <div
        v-if="type === 'color'"
        class="absolute right-[4px] top-1/2 -mt-3 w-6 h-6 rounded-md border border-surface-300 dark:border-surface-600"
        :style="{ backgroundColor: previewColor }"
      ></div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, computed } from 'vue'
  import AutoComplete from 'primevue/autocomplete'
  import { useThemeStore } from '@/stores/useThemeStore'
  import { $dt } from '@primevue/themes'

  const themeStore = useThemeStore()

  // 生成唯一ID的函数
  const generateUniqueId = () => `dt_field_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`

  // 响应式数据
  const id = ref(generateUniqueId())
  const items = ref<any[] | undefined>([])

  // Props 定义
  interface Props {
    label?: string
    type?: string
    modelValue?: any
  }

  const props = withDefaults(defineProps<Props>(), {
    label: undefined,
    type: undefined,
    modelValue: undefined,
  })

  // Emits 定义
  const emit = defineEmits<{
    'update:modelValue': [value: any]
  }>()

  // 计算属性
  const previewColor = computed(() => {
    const tokenValue = typeof props.modelValue === 'object' ? props.modelValue.label : props.modelValue
    if (tokenValue && tokenValue.trim().length && tokenValue.startsWith('{') && tokenValue.endsWith('}')) {
      const token = tokenValue.slice(1, -1) // 移除 {} 括号
      return $dt(token).variable
    }
    return tokenValue
  })

  const inputId = computed(() => id.value + '_input')

  // pt 配置对象
  const ptConfig = {
    pcInputText: {
      root: [
        'border border-surface-300 dark:border-surface-600 rounded-lg py-2 px-2 w-full',
        { 'pr-8': props.type === 'color' },
      ],
    },
    overlay: 'border border-surface-200 dark:border-surface-700 bg-surface-0 dark:bg-surface-950 shadow-2 rounded-md',
    listContainer: 'max-h-40 overflow-auto',
    list: 'm-0 py-2 px-2 list-none',
    loader: 'hidden',
    option:
      'cursor-pointer py-1 text-sm text-surface-700 dark:text-white/80 data-[p-focus=true]:bg-surface-100 data-[p-focus=true]:dark:bg-surface-800 rounded-md',
  }

  // 方法
  const onOptionSelect = (event: any) => {
    emit('update:modelValue', event.value.label)
    event.originalEvent.stopPropagation()
  }

  const onInput = (event: any) => {
    emit('update:modelValue', event.target.value)
  }

  const search = (event: { query: string }) => {
    const query = event.query
    if (query.startsWith('{')) {
      items.value = themeStore.acTokens.filter(t => t.label.startsWith(query))
    } else {
      items.value = []
    }
  }
</script>
